package butines.core.game.steering;

import java.util.LinkedList;

import butines.core.game.Vehicle;
import butines.core.math.Vector2f;

public class PriorityCombinationBehavior implements Behavior {

	private LinkedList<AbstractBehavior> behaviors = new LinkedList<AbstractBehavior>();

	private Vehicle owner;
	
	private Vector2f steeringForce = new Vector2f();
	
	public PriorityCombinationBehavior(Vehicle owner) {
		this.owner = owner;
	}

	public Vector2f calculate() {
		steeringForce.set(0, 0);
		for (AbstractBehavior behavior : getBehaviors()) {
			if (behavior.isTurned()) {
				float weight = behavior.getWeight();
				Vector2f force = behavior.calculate().mult(weight);
				if (accumulateForce(force)) {
					break;
				}
			}
		}
		return steeringForce;
	}

	private boolean accumulateForce(Vector2f force) {
		float magnitudeRemannig = owner.getMaxForce() - steeringForce.length();
		if (magnitudeRemannig <= 0f) {
			return true;
		}
		float magnitudeToAdd = force.length();
		if (magnitudeToAdd < magnitudeRemannig) {
			steeringForce.add(force);
		} else {
			force.normalise();
			Vector2f.multAdd(force, magnitudeRemannig, steeringForce);
		}
		return false;
	}

	public void addBehavior(AbstractBehavior behavior, float weight) {
		behaviors.add(behavior);
		behavior.setWeight(weight);
	}

	public LinkedList<AbstractBehavior> getBehaviors() {
		return behaviors;
	}
	
}
